package com.xm9m.web.service.controller;

import com.salesmanager.core.constants.Constants;
import com.salesmanager.core.utils.CoreConfiguration;
import com.salesmanager.core.utils.MD5Util;
import com.xm9m.web.service.constants.RestApiConstants;
import com.xm9m.web.service.constants.StatusCode;
import com.xm9m.web.service.interfaces.IRestApi;
import com.xm9m.web.service.interfaces.IXm9mResponse;
import com.xm9m.web.service.internal.util.BuildResponseUtil;
import com.xm9m.web.service.utils.Base64Utils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.IClassFileProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

/**
 * Created by Liutong on 12/16/15.
 */
@RestController
public class RESTApiController extends AbstractRestApiController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RESTApiController.class);

    @Autowired
    private RestApiConstants apiConstants;

    @Resource
    private CoreConfiguration configuration;

    /**
     * GET请求入口
     *
     * @param apiName
     * @param version
     * @param request
     * @return
     */
    @RequestMapping(value = "/{apiName}/{version}", method = RequestMethod.GET)
    public IXm9mResponse restApiGetEnter(@PathVariable("apiName") String apiName,
                                         @PathVariable("version") String version,
                                         @RequestParam(value = "data", required = false) String data,
                                         @RequestParam(value = "sign", required = false) String sign,
                                         @RequestParam(value = "st", required = false) Long st,
                                         @RequestParam(value = "deviceId", required = false) String deviceId,
                                         @RequestParam(value = "userId", required = false) Long userId,
                                         HttpServletRequest request) throws Exception {
        IXm9mResponse xm9mResponse;

//        非Debug模式 验证sign ,获得版本信息接口除外
        LOGGER.info("接口名称：{}", apiName);
        if (!apiName.equals("zf.app.version.info.get")  &&
                (configuration.getProperty(Constants.APIS_DEBUG) == null || !configuration.getProperty(Constants.APIS_DEBUG).equals("true"))){
            if (StringUtils.isBlank(sign) || st == null) {
                return BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
            }
            LOGGER.info("参数data解密前:{}", data);
            if (data!=null){
                data = Base64Utils.decode(data);
            }
            LOGGER.info("Base64解密，解密后data:{}", data);
            String myData = data == null ? "" : data;
            String mySign = MD5Util.getStringMD5(myData + st / 1000 + coreConfiguration.getProperty(com.salesmanager.web.constants.Constants.RECAPATCHA_PRIVATE_KEY) + deviceId);
            if (mySign == null || !mySign.equals(sign)) {
                return BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
            }
        }

        IRestApi restApi = apiConstants.getApisGet().get(apiName);

        Long startTime = System.currentTimeMillis();
        if (restApi != null){
            restApi.setHttpServletRequest(request);
            //设置签名
            restApi.setSign(sign);
            //设置时间戳
            restApi.setSt(st);
            //设置设备ID
            restApi.setDeviceId(deviceId);
            //设置用户ID
            restApi.setUserId(userId);

            xm9mResponse = restApi.execute(data,version);
            LOGGER.info("接口名称：" + apiName + ",传入参数" + data + "本次请求共花费：" + (System.currentTimeMillis() - startTime) + "ms");
        } else {
            xm9mResponse = BuildResponseUtil.buildSimpleResponse(StatusCode.NOT_FOUND);
        }

        return xm9mResponse;
    }

    /**
     * POST 请求入口
     *
     * @param apiName
     * @param version
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/{apiName}/{version}", method = RequestMethod.POST)
    public IXm9mResponse restApiPostEnter(@PathVariable("apiName") String apiName,
                                          @PathVariable("version") String version,
                                          @RequestParam(value = "data", required = false) String data,
                                          @RequestParam(value = "sign", required = false) String sign,
                                          @RequestParam(value = "st", required = false) Long st,
                                          @RequestParam(value = "deviceId", required = false) String deviceId,
                                          @RequestParam(value = "userId", required = false) Long userId,
                                          HttpServletRequest request,
                                          HttpServletResponse response) throws Exception {

        LOGGER.info("接口名称：{}", apiName);
        //非Debug模式 验证sign ,获得版本信息接口除外
        if (configuration.getProperty(Constants.APIS_DEBUG) == null || !configuration.getProperty(Constants.APIS_DEBUG).equals("true")){
            if (StringUtils.isBlank(sign) || st == null) {
                return BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
            }
            LOGGER.info("&&&&&data:{}", data);
            if (data!=null){
                data = Base64Utils.decode(data);
            }
            LOGGER.info("Base64解密，解密后data:{}", data);
            String myData = data == null ? "" : data;
            String mySign = MD5Util.getStringMD5(myData + st / 1000 + coreConfiguration.getProperty(com.salesmanager.web.constants.Constants.RECAPATCHA_PRIVATE_KEY) + deviceId);
            if (mySign == null || !mySign.equals(sign)) {
                return BuildResponseUtil.buildSimpleResponse(StatusCode.PARAM_WRONG);
            }
        }


        IXm9mResponse xm9mResponse;

        IRestApi restApi = apiConstants.getApisPost().get(apiName);

        Long startTime = System.currentTimeMillis();
        if (restApi != null){
            restApi.setHttpServletRequest(request);
            //设置签名
            restApi.setSign(sign);
            //设置时间戳
            restApi.setSt(st);
            //设置设备ID
            restApi.setDeviceId(deviceId);
            //设置用户ID
            restApi.setUserId(userId);

            xm9mResponse = restApi.execute(data,version);
            LOGGER.info("接口名称：" + apiName + ",传入参数" + data + "本次请求共花费：" + (System.currentTimeMillis() - startTime) +"ms");
        } else {
            xm9mResponse = BuildResponseUtil.buildSimpleResponse(StatusCode.NOT_FOUND);
        }

        return xm9mResponse;
    }
}
